package com.sk.restree.model.action;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import com.sk.restree.model.dao.BenefitDAO;
import com.sk.restree.model.dao.MenuDAO;
import com.sk.restree.model.dto.BenefitDTO;
import com.sk.restree.model.dto.MenuDTO;

public class MenuListAction implements Action {

	@Override
	public Object execute(HttpServletRequest request,
			HttpServletResponse response) {
		String store_id = request.getParameter("storeid");
		String card_id = request.getParameter("card_id");
		MenuDAO dao = MenuDAO.getInstance();

		Map<String, Object> json = new HashMap<String, Object>();

		setMenu(store_id, dao, json);

		BenefitDAO benefitDao = BenefitDAO.getInstance();
		BenefitDTO benefitDto = benefitDao.getBenefit(card_id, store_id);
		if(benefitDto != null){
			json.put("percent", benefitDto == null ? "0" : benefitDto.getPercent());
			json.put("store_open", benefitDto.getStore_open());
			json.put("store_close", benefitDto.getStore_close());
		}else{
			json.put("percent", "0");
			json.put("store_open", "none");
			json.put("store_close", "none");
		}
		
		json.put("percent", benefitDto == null ? "0" : benefitDto.getPercent());
		ObjectMapper om = new ObjectMapper();
		try {
			om.writeValue(response.getWriter(), json);
		} catch (JsonGenerationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JsonMappingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	private void setMenu(String store_id, MenuDAO dao, Map<String, Object> json) {
		List<MenuDTO> list = dao.getMenuList(store_id);
		List<Map<String, String>> menu = new ArrayList<Map<String, String>>();
		for (MenuDTO dto : list) {
			Map<String, String> map = new HashMap<String, String>();
			map.put("menu_id", dto.getMenu_id());
			map.put("menu_name", dto.getMenu_name());
			map.put("msize", dto.getMsize());
			map.put("price", dto.getPrice());
			map.put("store_id", dto.getStore_id());
			menu.add(map);
		}
		json.put("menu", menu);
	}

}
